package com.imaker.service;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.imaker.dao.BaseDao;
import com.imaker.domain.ActionOperateInfo;
import com.imaker.domain.RoleActionOperateInfo;
import com.imaker.domain.RoleInfo;

 /**
 * <p>程序名称：       RoleActionOperateService</p>
 * <p>程序说明：       角色操作</p>
 * <p>版权信息：       Copyright mayonghua</p>
 * 
 * @author：          mayonghua
 * @version：         Ver 0.1
 */
@Service
public class RoleActionOperateService implements IService {
	private BaseDao<RoleActionOperateInfo> roleActionOperateDAO = null;
	private BaseDao<ActionOperateInfo> actionOperateDAO = null;
	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		roleActionOperateDAO = new BaseDao<RoleActionOperateInfo>(sessionFactory,RoleActionOperateInfo.class);
		actionOperateDAO = new BaseDao<ActionOperateInfo>(sessionFactory,ActionOperateInfo.class);
	}
	
	//更新角色
	public void update(List<String> idList,String flag,String roldId) throws Exception{
		for(String id : idList){
		//首先判断有没有该条数据
		String hql = "from RoleActionOperateInfo raoi where raoi.actionOperate.id = ? and raoi.role.id=?";
		List<RoleActionOperateInfo> list = roleActionOperateDAO.find(hql,id,roldId);
		//启用
		if("T".equals(flag)){
			//首先判断有没有，有则更新，没有则新建
			if(list.size()>0){
				RoleActionOperateInfo raoi = list.get(0);
				raoi.setState("T");
				roleActionOperateDAO.update(raoi);
			}else {
				RoleActionOperateInfo raoi = new RoleActionOperateInfo();
				ActionOperateInfo aoi = actionOperateDAO.get(id);
				RoleInfo ri = new RoleInfo();
				ri.setId(roldId);
				raoi.setActionOperate(aoi);
				raoi.setRole(ri);
				raoi.setWebId(aoi.getWebId());
				raoi.setState("T");
				roleActionOperateDAO.save(raoi);
			}
		}else if("F".equals(flag)){
			if(list.size()>0){
				RoleActionOperateInfo raoi = list.get(0);
				raoi.setState("F");
				roleActionOperateDAO.update(raoi);
			}else {
				
			}
			
		}
	}
}
	
	/**
	 * 
	 * @param roleInfo
	 * @return
	 */
	public List<RoleActionOperateInfo> findByRole(String roleId) throws Exception{
		String hql = "from RoleActionOperateInfo raoi where raoi.role.id = ? and raoi.state = ?";
		return roleActionOperateDAO.find(hql, roleId,"T");
	} 
}
